#!/usr/bin/env python
# -*- coding: utf-8 -*-

from mm import *

class Mm_vCard(Mm):
	
	def __init__(self, file):
		conf = self.parse(file)
		self.set_status(conf[0])
		
		
	def read(self, _file = None):
		result = None
		
		if not _file:
			_file = self.get_status()
			
		try:
			of = open(_file, "r")
			result = self.parsevCard(of)
			self.data = result[1:]
			of.close()
		except IOError:
			print "I can not open file ", _file
		
		return result
			
	def parsevCard(self, opened_file):
		lines = []
		
		#odstraneni neplatnych radku
		for l in opened_file.readlines():
			if ':' in l:
				lines.append(l)
		
		i = j = max_length = 0
		data = []
		data.append({})
		
		for line in lines:
			splitted_line = line.split(':')
			attribut = splitted_line[0].upper()
			value = splitted_line[1]
			
			if i == 1:
				if not attribut in ["BEGIN", "END"]:
					data[0][attribut] = "None"
			
			if attribut == "BEGIN":
				data.append({})
				i += 1
			elif attribut == "END":
				if j > max_length:
					max_length = j
			else:
				data[i][attribut] = value
				j += 1
			
		def dopln(dict, spec):
			spec = spec.keys()
			for item in spec:
				if not item in dict.keys():
					dict[item] = "None"
					
		new_data = []
		new_data.append(data[0].keys())
		
		for item in data[1:]:
			dopln(item, data[0])
			new_data.append(item.values())
		
		return new_data



if __name__ == '__main__':
	cv = Mm_vCard("/home/bobin/bin/skola/bakalar/70317/data/std.vcf")
	print cv.read()
